package com.zzyl.serve.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.serve.service.IWecharService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信小程序工具组件接口
 *
 * @author makangkang
 * @date 2025/10/22 15:44
 */
@Service
public class WecharServiceImpl implements IWecharService {

    @Value("${wechat.appId}")
    private String appId;
    @Value("${wechat.secret}")
    private String secret;

    private static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token";
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    /**
     * 获取openId
     *
     * @return
     */
    @Override
    public String getOpenId(String code) {
        Map<String, Object> paramMap = getAppidAndSecret();
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");

        String result = HttpUtil.get(OPENID_URL, paramMap);
        if (StringUtils.isBlank(result)) {
            throw new BaseException("获取openId失败");
        }

        JSONObject jsonObject = JSONUtil.parseObj(result);
        String openId = jsonObject.getStr("openid");

        return openId;
    }

    /**
     * 获取appid和secret
     *
     * @return
     */
    private Map<String, Object> getAppidAndSecret() {
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appId);
        map.put("secret", secret);
        return map;
    }

    /**
     * 获取微信小程序的访问Token
     *
     * @return
     */
    private String getAccessToken() {
        Map<String, Object> paramMap = getAppidAndSecret();
        paramMap.put("grant_type", "client_credential");

        String result = HttpUtil.get(ACCESS_TOKEN, paramMap);
        if (StringUtils.isBlank(result)) {
            throw new BaseException("获取微信小程序的访问Token失败");
        }

        JSONObject jsonObject = JSONUtil.parseObj(result);
        String accessToken = jsonObject.getStr("access_token");
        return accessToken;
    }

    /**
     * 获取手机号
     *
     * @return
     */
    @Override
    public String getPhone(String code) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        String paramMap = JSON.toJSONString(map);
        String result = HttpUtil.post(PHONE_URL + getAccessToken(), paramMap);

        if (StringUtils.isBlank(result)) {
            throw new BaseException("获取返回值异常");
        }


        JSONObject jsonObject = JSONUtil.parseObj(result);
        JSONObject phoneInfoJson = jsonObject.getJSONObject("phone_info");
        if (phoneInfoJson == null) {
            // 校验对象是否存在
            throw new BaseException("获取手机号失败");
        }
        String phoneNumber = phoneInfoJson.getStr("phoneNumber");
        return phoneNumber;
    }

}

